package com.mbbb.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mbbb.yygh.common.exception.YyghException;
import com.mbbb.yygh.hosp.repository.ScheduleRepository;
import com.mbbb.yygh.hosp.service.DepartmentService;
import com.mbbb.yygh.hosp.service.HospitalService;
import com.mbbb.yygh.hosp.service.ScheduleService;
import com.mbbb.yygh.model.hosp.BookingRule;
import com.mbbb.yygh.model.hosp.Department;
import com.mbbb.yygh.model.hosp.Hospital;
import com.mbbb.yygh.model.hosp.Schedule;
import com.mbbb.yygh.vo.hosp.BookingScheduleRuleVo;
import com.mbbb.yygh.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;


    //更新排班数据
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //根据排班id获取排班数据
        Schedule schedule = this.getScheduleById(scheduleId);
        //获取医院对象和预约规则
        Hospital hospital = hospitalService.getHospHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(20001,"医院不存在");
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //设置scheduleOrderVo的数据
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    //获取排班详情
    @Override
    public Schedule getScheduleById(String id) {
        return this.packageSchedule(scheduleRepository.findById(id).get());
    }

    //根据医院编号 + 科室编号查询，分页显示
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //1.获取所有可以显示的日期（当前日期 + 预约周期）（分页显示）
        //①先根据医院编号，获取医院对象,再根据医院对象，获取预约规则数据（包含预约周期）
        Hospital hospital = hospitalService.getHospHoscode(hoscode);
        if (hospital == null)
            throw new YyghException(20001,"医院不存在");

        BookingRule bookingRule = hospital.getBookingRule();
        Integer cycle = bookingRule.getCycle();
        //②获取所有可以显示的日期（当前日期 + 预约周期）（分页显示）（目前不包含是否有号）
        //⭐使用baomidou的IPage，IPage可以携带分页数据，方便分页
        IPage iPage = this.getListDate(page, limit, bookingRule);
        //每页显示的日期数据的集合
        List<Date> dateList = iPage.getRecords();

        //2.根据显示的日期查询mongodb，看日期内是否有号的数据
        //封装mongoTemplate聚合条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                                    .and("depcode").is(depcode)
                                    .and("workDate").in(dateList);
        Aggregation aggregation = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //根据workDate分组
                Aggregation.group("workDate")
                                .first("workDate")
                                .as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        //调用MongoTemplate方法实现聚合查询得到结果
        AggregationResults<BookingScheduleRuleVo> aggregateResult =
                mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleList = aggregateResult.getMappedResults();

        //3.根据所有显示的日期，查询集合比对日期是否有数据，有数据显示有号，否则显示无号
        //stream流转换map集合 key：日期   value：日期对应的数据
        Map<Date, BookingScheduleRuleVo> scheduleVoMap =
                scheduleList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));

        //4.拿着需要显示的日期，到scheduleVoMap集合中比对，有数据显示有号，否则显示无号
        //存放最终显示日期数据
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        //遍历显示日期的集合
        for (int i=0,len=dateList.size();i<len;i++) {
            //获取每个日期
            Date date = dateList.get(i);
            //到scheduleVoMap集合中比对
            //key就是日期，使用get方法查询，不为空就是有数据
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //如果日期每有对应的数据，表示该日期没有号
            if (bookingScheduleRuleVo == null) {
                //无号设置
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //设置日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //日期对应的星期
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   0：正常 1：即将放号 -1：当天已停止挂号
            if(i==len-1 && page==iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //判断第一页第一条记录是否过了停挂时间，如果过了，设置为停止挂号
            if (i==0 & page==1) {
                //获取今天的停挂时间
                DateTime stopTime = this.getDateTime(new Date(),bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止挂号
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            //最终日期显示集合（包含有号，无号）
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //4.返回需要的数据
        Map<String, Object> result = new HashMap<>();
        //可预约日期集合数据（最终数据）
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        //总记录数
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //②获取所有可以显示的日期（当前日期 + 预约周期）（分页显示）（目前不包含是否有号）
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //1.获取当前日期 + 放号时间 例：2021-12-20 8:30
        DateTime dateTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //2.获取预约周期
        Integer cycle = bookingRule.getCycle();
        //3.判断：如果当前日期过了放号时间，就让预约周期 +1
        if (dateTime.isBeforeNow()) //dateTime的日期时间在当前日期时间之前
            cycle += 1;

        //4.得到显示日期数据
        //用于存放日期数据
        List<Date> dateList = new ArrayList<>();
        //根据预约周期循环
        for (int i = 0; i < cycle; i++) {
             //计算当前预约日期
            DateTime dateTime1 = new DateTime().plusDays(i);
            String dateTime1String = dateTime1.toString("yyyy-MM-dd");
            Date date = new DateTime(dateTime1String).toDate();
            //每次天数相加，都添加到list集合中
            dateList.add(date);
        }

        //5.分页显示
        //用于存放分页显示的日期数据
        List<Date> pageDateList = new ArrayList<>();
        //设置每页开始位置
        int start = (page-1)*limit;
        //设置每页结束位置
        int end = (page-1)*limit+limit;
        //每页记录数如果大于集合长度，每页记录数就是集合长度
        if(end >dateList.size()) {
            end = dateList.size();
        }
        //封装每页显示数据的list集合
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }

        IPage<Date> iPage =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,7,dateList.size());
        //设置每页数据的list集合
        iPage.setRecords(pageDateList);
        return iPage;
    }

    //根据医院编号 、科室编号和工作日期，查询排班详细信息
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {

        //String workDate --> Date workDate
        Date dateWorkDate = new DateTime(workDate).toDate();
        List<Schedule> list =
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,dateWorkDate);
        list.stream().forEach(item -> {
            this.packageSchedule(item);
        });
        return list;
    }

    //封装医院和科室名称 星期
    private Schedule packageSchedule(Schedule schedule) {
        //查询医院名称
        String hospName = hospitalService.getHospName(schedule.getHoscode());
        //科室名称
        String deptName = departmentService.getDeptName(schedule.getHoscode(),schedule.getDepcode());
        //封装
        schedule.getParam().put("hosname",hospName);
        schedule.getParam().put("depname",deptName);
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    //根据医院编号 + 科室编号查询可预约日期数据（分页）
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {

        //1.MongoTemplate封装查询条件医院编号 + 科室编号
        //springboot 整合mongoTemplate的 Query和Criteria
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2.MongoTemplate封装"聚合"条件过程
        Aggregation aggregation = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //分组 根据workDate
                Aggregation.group("workDate")
                            .first("workDate").as("workDate")
                            //统计数据
                            .count().as("docCount")
                            //求和  预约  和 剩余数量
                            .sum("reservedNumber").as("reservedNumber")
                            .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                //分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //3.调用MongoTemplate方法实现聚合查询得到结果
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);

        //预约规则集合BookingScheduleRuleVo
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();

        //把日期对应的星期dayOfWeek封装到集合中
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            //获取每个对象的日期
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            //工具方法
            // Date  -->  DateTime
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            //封装
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //获取总记录数
        Aggregation totalAggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggregate =
                mongoTemplate.aggregate(totalAggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> list = totalAggregate.getMappedResults();
        //总记录数
        int total = list.size();

        //4 把得到所有结果封装map集合，返回result
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleVoList",bookingScheduleRuleVoList);
        result.put("total",total);
        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);

        result.put("baseMap",baseMap);
        return result;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    //删除排班
    @Override
    public void deleteSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    //获取排班分页列表
    @Override
    public Page<Schedule> selectSchedulePage(int page, int limit) {

        //设置排序
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        //设置分页
        //0为第一页（当前页）
        PageRequest pageRequest = PageRequest.of(page-1, limit, sort);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Schedule schedule = new Schedule();
        schedule.setHoscode("10000");

        Example<Schedule> example = Example.of(schedule, matcher);

        Page<Schedule> schedulePage = scheduleRepository.findAll(example, pageRequest);

        return schedulePage;
    }


    //上传排班
    @Override
    public void saveSchedule(Map<String, Object> stringObjectMap) {

        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        Schedule existSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());

        if (existSchedule != null) {
            schedule.setId(existSchedule.getId());
            schedule.setCreateTime(existSchedule.getCreateTime());
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }
}
